//
//  EmptyDataSet.swift
//  SwiftExercise
//
//  Created by 罗宗庆 on 2021/6/24.
//

import Foundation
import EmptyDataSet_Swift

extension UIScrollView{
    
    private struct AssociateKeys{
        static var emptyKey:Void?
    }
    var emptyView:EmptyView?{
        get{
            return objc_getAssociatedObject(self, &AssociateKeys.emptyKey) as? EmptyView
        }
        set{
            self.emptyDataSetSource  = newValue
            self.emptyDataSetDelegate = newValue
            objc_setAssociatedObject(self, &AssociateKeys.emptyKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
    
}

class EmptyView: EmptyDataSetSource,EmptyDataSetDelegate {
    var image:UIImage?
    var allowShow:Bool = true
    var verticalOffset:CGFloat = 0
    
    private var tapClosure:(()->Void)?
    
    init(image:UIImage? = UIImage(named: "icon_foursquare"),verticalOffset:CGFloat = 0,tapClosure:(()->Void)?) {
        self.image = image
        self.verticalOffset = verticalOffset
        self.tapClosure = tapClosure
    }
    
    func verticalOffset(forEmptyDataSet scrollView: UIScrollView) -> CGFloat {
        return verticalOffset
    }
    
    func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
        return image
    }
    
    func emptyDataSetShouldDisplay(_ scrollView: UIScrollView) -> Bool {
        return allowShow
    }
    
    func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
        
        var attributes:[NSAttributedString.Key:Any] = [:]
        attributes[NSAttributedString.Key.font] = UIFont.systemFont(ofSize:20)
        attributes[NSAttributedString.Key.foregroundColor] = UIColor.red
        return NSAttributedString.init(string: "没有数据", attributes: attributes)
    }
    
    func emptyDataSet(_ scrollView: UIScrollView, didTapView view: UIView) {
        guard let tapClosure = tapClosure else { return }
        tapClosure()
    }
    
}
